<template>
    <div>
        <div style="display: flex; flex-flow: row;justify-content: space-between;align-items: center;">
            <a-breadcrumb style="margin: 16px 0">
                <a-breadcrumb-item>桌位预定</a-breadcrumb-item>
            </a-breadcrumb>
        </div>
        
        <!-- 上半部分：桌位表格 -->
        <div :style="{ padding: '24px', background: '#fff', marginBottom: '16px' }">
        <a-table 
            :columns="tableColumns" 
            :data-source="tableData"
            :pagination="false"
            :row-key="(record) => record.id"
            :loading="tableLoading"
        >
            <template #headerCell="{ column }">
                <template v-if="column.key === 'tableName'">
                    <span>
                        <table-outlined />
                        桌位号
                    </span>
                </template>
            </template>

            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'tableName'">
                    <a @click="selectTable(record)">{{ record.tableName }}</a>
                </template>
                <template v-else-if="column.key === 'status'">
                    <a-tag :color="getStatusColor(record.status)">
                        {{ getStatusText(record.status) }}
                    </a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                    <span>
                        <a @click="selectTable(record)">查看预定</a>
                        <a-divider type="vertical" />
                        <a v-if="record.status === 0" @click="showReserveModal(record)">预定</a>
                        <a v-else @click="endReservation(record)">预定结束</a>
                    </span>
                </template>
            </template>
        </a-table>
    </div>

    <!-- 下半部分：选定桌位的预定菜品 -->
    <div v-if="selectedTable" :style="{ padding: '24px', background: '#fff' }">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <div>
                <h3>桌位 {{ selectedTable.tableName }} 的预定菜品</h3>
                <p v-if="selectedTable.customerName" style="margin: 0; color: #666;">
                    预定用户：{{ selectedTable.customerName }} ({{ selectedTable.customerPhone }})
                </p>
            </div>
            <a-button type="primary" @click="showAddDishModal">添加菜品</a-button>
        </div>
        
        <a-table 
            :columns="reservationColumns" 
            :data-source="reservationData"
            :pagination="false"
            :row-key="(record) => record.id"
            :row-selection="{ selectedRowKeys: selectedReservationKeys, onChange: onReservationSelect }"
            :loading="reservationLoading"
        >
            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                    <span>
                        <a @click="deleteReservation(record.id)">删除</a>
                        <a-divider type="vertical" />
                        <a @click="updateReservationStatus(record)">更新状态</a>
                    </span>
                </template>
                <template v-else-if="column.key === 'status'">
                    <a-tag :color="getReservationStatusColor(record.status)">
                        {{ getReservationStatusText(record.status) }}
                    </a-tag>
                </template>
            </template>
        </a-table>
        
        <!-- 总计和批量操作 -->
        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 16px; padding: 16px; background: #f5f5f5; border-radius: 6px;">
            <div>
                <strong>总计：¥{{ totalPrice.toFixed(2) }}</strong>
                <span style="margin-left: 16px; color: #666;">
                    共 {{ reservationData.length }} 个菜品
                </span>
            </div>
            <div>
                <a-button 
                    type="primary" 
                    :disabled="!selectedTable || selectedTable.status === 0"
                    @click="executeReservation"
                    style="margin-right: 8px;"
                >
                    预定执行
                </a-button>
                <a-button 
                    type="primary" 
                    danger
                    :disabled="selectedReservationKeys.length === 0"
                    @click="deleteSelectedReservations"
                >
                    批量删除 ({{ selectedReservationKeys.length }})
                </a-button>
            </div>
        </div>
    </div>

    <!-- 添加菜品模态框 -->
    <a-modal
        v-model:open="addDishModalVisible"
        title="添加预定菜品"
        @ok="handleAddDish"
        @cancel="handleCancelAddDish"
        :confirm-loading="addDishLoading"
    >
        <a-form :model="addDishForm" layout="vertical">
            <a-form-item label="选择菜品" name="dishId">
                <a-select
                    v-model:value="addDishForm.dishId"
                    placeholder="请选择菜品"
                    style="width: 100%"
                >
                    <a-select-option 
                        v-for="dish in availableDishes" 
                        :key="dish.id" 
                        :value="dish.id"
                    >
                        {{ dish.name }} - ¥{{ (dish.price / 100).toFixed(2) }} - {{ dish.type }}
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="数量" name="quantity">
                <a-input-number
                    v-model:value="addDishForm.quantity"
                    :min="1"
                    :max="99"
                    style="width: 100%"
                />
            </a-form-item>
        </a-form>
    </a-modal>

    <!-- 桌位预定模态框 -->
    <a-modal
        v-model:open="reserveModalVisible"
        title="桌位预定"
        @ok="handleReserveTable"
        @cancel="handleCancelReserve"
        :confirm-loading="reserveLoading"
    >
        <a-form :model="reserveForm" layout="vertical">
            <a-form-item label="预定用户姓名" name="customerName">
                <a-input
                    v-model:value="reserveForm.customerName"
                    placeholder="请输入预定用户姓名"
                />
            </a-form-item>
            <a-form-item label="预定用户电话" name="customerPhone">
                <a-input
                    v-model:value="reserveForm.customerPhone"
                    placeholder="请输入预定用户电话"
                />
            </a-form-item>
        </a-form>
    </a-modal>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { message } from 'ant-design-vue';
import { TableOutlined } from '@ant-design/icons-vue';
import { TableData, TableReservation, DishData } from '@/type/table';
import TableDao from '@/daos/table_dao';
import DishDao from '@/daos/dish_dao';

// 数据定义
const tableData = ref<TableData[]>([]);
const reservationData = ref<TableReservation[]>([]);
const availableDishes = ref<DishData[]>([]);
const selectedTable = ref<TableData | null>(null);
const selectedTableKeys = ref<number[]>([]);
const selectedReservationKeys = ref<number[]>([]);

// 加载状态
const tableLoading = ref(false);
const reservationLoading = ref(false);
const addDishLoading = ref(false);
const reserveLoading = ref(false);

// 添加预定菜品弹窗
const addDishModalVisible = ref(false);
const addDishForm = reactive({
    dishId: undefined as number | undefined,
    quantity: 1
});

// 显示桌位预定用户弹窗
const reserveModalVisible = ref(false);
const reserveForm = reactive({
    customerName: '',
    customerPhone: ''
});
const selectedTableForReserve = ref<TableData | null>(null);

// DAO实例
const tableDao = new TableDao();
const dishDao = new DishDao();

// 桌位表格列定义
const tableColumns = [
    {
        title: '桌位',
        dataIndex: 'tableName',
        key: 'tableName',
        align: 'center' as const,
        width: 120,
    },
    {
        title: '容量',
        dataIndex: 'amount',
        key: 'amount',
        align: 'center' as const,
        width: 100,
    },
    {
        title: '位置',
        dataIndex: 'location',
        key: 'location',
        align: 'center' as const,
        width: 150,
    },
    {
        title: '预定用户',
        key: 'customerName',
        align: 'center' as const,
        width: 150,
        customRender: ({ record }: { record: any }) => {
            if (record.customerName) {
                return `${record.customerName} (${record.customerPhone})`;
            }
            return '-';
        }
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center' as const,
        width: 120,
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        align: 'center' as const,
        width: 150,
    },
];

// 预定菜品表格列定义
const reservationColumns = [
    {
        title: '菜品名称',
        dataIndex: 'dishName',
        key: 'dishName',
        align: 'center' as const,
        width: 150,
    },
    {
        title: '价格',
        dataIndex: 'dishPrice',
        key: 'dishPrice',
        align: 'center' as const,
        width: 100,
        customRender: ({ text }: { text: number }) => `¥${(text / 100).toFixed(2)}`
    },
    {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        align: 'center' as const,
        width: 80,
    },
    {
        title: '小计',
        key: 'subtotal',
        align: 'center' as const,
        width: 100,
        customRender: ({ record }: { record: TableReservation }) =>
            record.dishPrice && record.quantity
                ? `¥${((record.dishPrice * record.quantity) / 100).toFixed(2)}`
                : '¥0.00'
    },
    {
        title: '预定时间',
        dataIndex: 'reservationTime',
        key: 'reservationTime',
        align: 'center' as const,
        width: 180,
        customRender: ({ record }: { record: TableReservation }) => formatTime(record.reservationTime)
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center' as const,
        width: 100,
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        align: 'center' as const,
        width: 120,
    },
];

// 时间格式化工具函数
function formatTime(val: string | number | undefined): string {
    if (!val) return '';
    const date = typeof val === 'number'
        ? new Date(val)
        : new Date(val.toString().replace(/-/g, '/'));
    if (isNaN(date.getTime())) return '';
    return date.getFullYear() + '-' +
        String(date.getMonth() + 1).padStart(2, '0') + '-' +
        String(date.getDate()).padStart(2, '0') + ' ' +
        String(date.getHours()).padStart(2, '0') + ':' +
        String(date.getMinutes()).padStart(2, '0') + ':' +
        String(date.getSeconds()).padStart(2, '0');
}

// 状态相关方法
const getStatusColor = (status: number) => {
    switch (status) {
        case 0: return 'green';
        case 1: return 'orange';
        case 2: return 'red';
        default: return 'default';
    }
};

const getStatusText = (status: number) => {
    switch (status) {
        case 0: return '空闲';
        case 1: return '已预定';
        case 2: return '使用中';
        default: return '未知';
    }
};

const getReservationStatusColor = (status: number) => {
    switch (status) {
        case 0: return 'blue';
        case 1: return 'green';
        case 2: return 'red';
        default: return 'default';
    }
};

const getReservationStatusText = (status: number) => {
    switch (status) {
        case 0: return '待确认';
        case 1: return '已确认';
        case 2: return '已取消';
        default: return '未知';
    }
};

// 初始化桌位数据
const init = async () => {
    tableLoading.value = true;
    try {
        const result = await tableDao.listAllTables();
        console.log('桌位数据:', result);
        
        if (result.data && result.data.data) {
            result.data.data.forEach((element: any) => {
                element.key = element.id.toString();
                element.tableName = element.tableName || '';
                element.amount = element.amount || 0;
                element.location = element.location || '';
                // 兼容下划线和驼峰
                element.customerName = element.customerName || '';
                element.customerPhone = element.customerPhone || '';
                element.createTime = new Date(element.createTime);
                element.status = element.status || 0;
            });
            tableData.value = result.data.data;
        } else {
            tableData.value = [];
        }
    } catch (error) {
        console.error('加载桌位数据错误:', error);
        message.error('加载桌位数据失败');
        tableData.value = [];
    } finally {
        tableLoading.value = false;
    }
};

// 桌位选择
const onTableSelect = (selectedKeys: number[]) => {
    selectedTableKeys.value = selectedKeys;
};

// 预定菜品选择
const onReservationSelect = (selectedKeys: number[]) => {
    selectedReservationKeys.value = selectedKeys;
};

// 计算总价格
const totalPrice = computed(() => {
    return reservationData.value.reduce((total, reservation) => {
        return total + (reservation.dishPrice * reservation.quantity);
    }, 0) / 100; // 转换为元
});

const selectTable = async (table: any) => {
    // 用 tableData 里的最新对象
    const latest = tableData.value.find(t => t.id === table.id);
    selectedTable.value = latest || table;
    selectedTableKeys.value = [table.id];
    // 清空预定菜品的选择状态
    selectedReservationKeys.value = [];
    await loadTableReservations(table.id);
};

// 加载桌位预定数据
const loadTableReservations = async (tableId: number) => {
    reservationLoading.value = true;
    try {
        const result = await tableDao.getTableReservations(tableId);
        console.log('预定数据:', result);
        
        if (result.data && result.data.data) {
            reservationData.value = result.data.data;
        } else {
            reservationData.value = [];
        }
    } catch (error) {
        console.error('加载预定数据错误:', error);
        message.error('加载预定数据失败');
        reservationData.value = [];
    } finally {
        reservationLoading.value = false;
    }
};

// 加载可用菜品
const loadAvailableDishes = async () => {
    try {
        const result = await dishDao.listAllDishes();
        console.log('菜品数据:', result);
        
        if (result.data && result.data.data) {
            availableDishes.value = result.data.data;
        } else {
            availableDishes.value = [];
        }
    } catch (error) {
        console.error('加载菜品数据错误:', error);
        message.error('加载菜品数据失败');
        availableDishes.value = [];
    }
};

// 添加菜品预定
const showAddDishModal = () => {
    addDishForm.dishId = undefined;
    addDishForm.quantity = 1;
    addDishModalVisible.value = true;
};

const handleAddDish = async () => {
    if (!addDishForm.dishId || !selectedTable.value) {
        message.error('请选择菜品和桌位');
        return;
    }

    addDishLoading.value = true;
    try {
        const result = await tableDao.addTableReservation({
            tableId: selectedTable.value.id,
            dishId: addDishForm.dishId,
            quantity: addDishForm.quantity
        });
        console.log('添加预定数据:', result.data);
        if (result.data && result.data.code === 200) {
            message.success('添加预定成功');
            addDishModalVisible.value = false;
            console.log(result.data);
            // 重新加载预定数据
            await loadTableReservations(selectedTable.value.id);
            
            // 清空选择
            selectedReservationKeys.value = [];
        } else {
            message.error('添加预定失败');
        }
    } catch (error) {
        console.error('添加预定错误:', error);
        message.error('添加预定失败');
    } finally {
        addDishLoading.value = false;
    }
};

const handleCancelAddDish = () => {
    addDishModalVisible.value = false;
    // 重置表单
    addDishForm.dishId = undefined;
    addDishForm.quantity = 1;
};

// 删除预定
const deleteReservation = async (reservationId: number) => {
    try {
        const result = await tableDao.deleteTableReservation(reservationId);
        
        if (result.data && result.data.code === 200) {
            message.success('删除预定成功');
            
            // 重新加载预定数据
            if (selectedTable.value) {
                await loadTableReservations(selectedTable.value.id);
            }
        } else {
            message.error('删除预定失败');
        }
    } catch (error) {
        console.error('删除预定错误:', error);
        message.error('删除预定失败');
    }
};

// 更新桌位状态
const updateTableStatus = async (table: any) => {
    const tableData = table as TableData;
    const newStatus = (tableData.status + 1) % 3;
    try {
        const result = await tableDao.updateTableStatus(tableData.id, newStatus);
        
        if (result.data && result.data.code === 200) {
            message.success('更新桌位状态成功');
            await init(); // 重新加载桌位数据
        } else {
            message.error('更新桌位状态失败');
        }
    } catch (error) {
        console.error('更新桌位状态错误:', error);
        message.error('更新桌位状态失败');
    }
};

// 更新预定状态
const updateReservationStatus = async (reservation: any) => {
    const reservationData = reservation as TableReservation;
    const newStatus = (reservationData.status + 1) % 3;
    
    try {
        const result = await tableDao.updateReservationStatus(reservationData.id, newStatus);
        
        if (result.data && result.data.code === 200) {
            message.success('预定状态更新成功');
            // 重新加载预定数据
            if (selectedTable.value) {
                await loadTableReservations(selectedTable.value.id);
            }
        } else {
            message.error('预定状态更新失败');
        }
    } catch (error) {
        console.error('更新预定状态错误:', error);
        message.error('更新预定状态失败');
    }
};

// 批量删除预定
const deleteSelectedReservations = async () => {
    if (selectedReservationKeys.value.length === 0) {
        message.warning('请选择要删除的菜品');
        return;
    }

    try {
        // 批量删除选中的预定
        const deletePromises = selectedReservationKeys.value.map(id => 
            tableDao.deleteTableReservation(id)
        );
        
        await Promise.all(deletePromises);
        
        message.success(`成功删除 ${selectedReservationKeys.value.length} 个菜品`);
        selectedReservationKeys.value = [];
        
        // 重新加载预定数据
        if (selectedTable.value) {
            await loadTableReservations(selectedTable.value.id);
        }
    } catch (error) {
        console.error('批量删除错误:', error);
        message.error('批量删除失败');
    }
};

// 显示桌位预定模态框
const showReserveModal = (table: any) => {
    selectedTableForReserve.value = table as TableData;
    reserveForm.customerName = '';
    reserveForm.customerPhone = '';
    reserveModalVisible.value = true;
};

// 处理桌位预定
const handleReserveTable = async () => {
    if (!reserveForm.customerName || !reserveForm.customerPhone) {
        message.error('请填写完整的用户信息');
        return;
    }

    if (!selectedTableForReserve.value) {
        message.error('桌位信息错误');
        return;
    }

    reserveLoading.value = true;
    try {
        // 调用后端API进行桌位预定
        const result = await tableDao.reserveTable({
            tableId: selectedTableForReserve.value.id,
            customerName: reserveForm.customerName,
            customerPhone: reserveForm.customerPhone
        });
        console.log("用户数据：",selectedTableForReserve.value.id,reserveForm.customerName,reserveForm.customerPhone);
        if (result.data && (result.data.success || result.data.code === 200)) {
            message.success('桌位预定成功');
            reserveModalVisible.value = false;
            await init(); // 重新加载桌位数据
            // 重新选中当前桌位，确保 selectedTable 是最新的
            await selectTable({ id: selectedTableForReserve.value.id });
        } else {
            message.error(result.data?.message || '桌位预定失败');
        }
    } catch (error) {
        console.error('预定错误:', error);
        message.error('预定失败');
    } finally {
        reserveLoading.value = false;
    }
};

// 取消桌位预定
const handleCancelReserve = () => {
    reserveModalVisible.value = false;
    selectedTableForReserve.value = null;
};

// 结束预定（预定结束）
const endReservation = async (table: any) => {
    const tableData = table as TableData;
    try {
        // 调用后端API结束预定
        const result = await tableDao.endReservation(tableData.id);

        if (result.data && result.data.code === 200) {
            message.success('预定已结束，桌位已清空');
            await init(); // 重新加载桌位数据
            
            // 如果当前选中的是这个桌位，清空选择
            if (selectedTable.value && selectedTable.value.id === tableData.id) {
                selectedTable.value = null;
                selectedReservationKeys.value = [];
            }
        } else {
            message.error('结束预定失败');
        }
    } catch (error) {
        console.error('结束预定错误:', error);
        message.error('结束预定失败');
    }
};

// 预定执行（将桌位状态改为使用中）
const executeReservation = async () => {
    if (!selectedTable.value) {
        message.error('请先选择桌位');
        return;
    }

    if (selectedTable.value.status === 0) {
        message.error('空闲桌位无法执行预定');
        return;
    }

    try {
        // 调用后端API执行预定
        const result = await tableDao.executeReservation(selectedTable.value.id);

        if (result.data && result.data.code === 200) {
            message.success('预定已执行，桌位状态更新为使用中');
            await init(); // 重新加载桌位数据
        } else {
            message.error('执行预定失败');
        }
    } catch (error) {
        console.error('执行预定错误:', error);
        message.error('执行预定失败');
    }
};

// 初始化
onMounted(async () => {
    await init();
    await loadAvailableDishes();
});
</script>

<style scoped>
.ant-table-wrapper {
    margin-bottom: 16px;
}
</style>